package com.eight.cloud.auth.common.security.provider;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.auth.model.vo.CurrentUser;
import com.eight.cloud.auth.common.security.authentication.TenantUsernamePasswordAuthenticationToken;
import com.eight.cloud.core.global.model.LoginUser;
import com.eight.cloud.openfeign.admin.api.UserClient;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 多租户用户名密码登陆
 *
 * @ClassName: TenantUsernamePasswordAuthenticationProvider
 * @Author: TXC
 * @Date: 2024-12-23 16:46
 **/
public class TenantUsernamePasswordAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
    @Setter
    private UserClient userClient;
    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        TenantUsernamePasswordAuthenticationToken authenticationToken = (TenantUsernamePasswordAuthenticationToken) authentication;
        LoginUser loginUser = userClient.getUserinfo(String.valueOf(authenticationToken.getPrincipal()), String.valueOf(authenticationToken.getTenantId()));
        if (ObjectUtil.isNull(loginUser)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return new TenantUsernamePasswordAuthenticationToken(new CurrentUser(loginUser), loginUser.getPassword(), loginUser.getTenantId());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return TenantUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

    @Override
    public void afterPropertiesSet() {

    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messages = new MessageSourceAccessor(messageSource);
    }

}
